<template>
  <div
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <!-- <el-row>
      <el-col :span="24">
        <el-tabs
          v-model="staticsType"
          @tab-click="handleClick"
          class="text-tabs TTB-gutter"
        >
          <el-tab-pane
            v-for="(item, index) in tabArr"
            :key="index"
            :label="item.label"
            :name="item.value"
            v-hasPermi="[item.per]"
          ></el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row> -->
    <lb-layout>
      <aps-form
        :config="apsForm.formConfig"
        :model="apsForm.formData"
        :formRef="apsForm.formRef"
        :labelWidth="apsForm.labelWidth"
        ref="form"
      ></aps-form>
      <lb-table
        v-loading="$store.getters.loading"
        border
        height="700"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="#a19f9fb0;"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 40, 60, 80]"
        :pager-count="5"
        :current-page.sync="currentPage"
        :total="total"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>
    </lb-layout>
    <detailPop
      :visible.sync="visible"
      :id="rowID"
      :waytype="staticsType"
      @close="close"
    />
  </div>
</template>

<script>
import { getList, deleteSub, putSubstatus } from "@/api/sub/manage";
import { deepClone, formatDate } from "@/utils/index";
import { getDicts } from "@/api/system/dict/data"; // 单独字典接口拎出来用来做分类分项的父子关系处理
import auth from "@/plugins/auth";
import DictionariesSelect from "@/components/DictionariesSelect/index.vue";
import detailPop from "@/views/configuration/standard/manage/components/detail.vue";
export default {
  components: {
    detailPop,
    DictionariesSelect,
  },
  dicts: [
    "energy_subarea_param_classify_type", // 分区分项参数管理类型
    "energy_subarea_status", // 分区分项状态
    "energy_measure_alone", // 是否单独计量

    "energy_family_splitting_type", // 分户类别
    "energy_subarea_type", // 分区类别
    "energy_subarea_child_type", // 分区子类
    "energy_type", // 分类类别-能耗类型
    "subentry_type", // 分项类别
  ],
  name: "subManage",
  data() {
    return {
      // 弹出层
      visible: false,
      rowID: null,
      deptList: [],
      deptId: "",
      staticsType: "1",
      // tabArr: [
      //   {
      //     label: "分户计量",
      //     value: "1",
      //     per: "",
      //   },
      //   {
      //     label: "分区计量",
      //     value: "2",
      //     per: "",
      //   },
      //   // {
      //   //   label: "分类计量",
      //   //   value: "3",
      //   //   per: "",
      //   // },
      //   {
      //     label: "分项计量",
      //     value: "4",
      //     per: "",
      //   },
      // ],
      networksId: "",
      apsForm: {
        formRef: "form",
        labelWidth: "80px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            // 状态 在用/停用
            status: {
              label: "状态:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    {
                      <DictionariesSelect
                        showType={0}
                        valueType={1}
                        datas={that.$refs?.form?.getFieldsValue().status}
                        selectArr={that.dict.type.energy_subarea_status}
                        onHandleSelect={(val) => {
                          that.$refs?.form?.setFieldValue("status", val);
                          that.$forceUpdate();
                        }}
                        clearable={true}
                        onHandleClear={(flage) => {
                          that.$refs?.form?.setFieldValue("status", null);
                          that.$forceUpdate();
                        }}
                        placeholder="请选择"
                      ></DictionariesSelect>
                    }
                  </div>
                );
              },
            },
            // date: {
            //   typeName: "el-date-picker",
            //   type: "datetime",
            //   size: "small",
            //   placeholder: "请选择创建时间",
            //   "value-format": "timestamp", // 时间戳
            //   "picker-options": {
            //     disabledDate: (time) => {
            //       // 禁用今天之后的日期(不包含今天)
            //       return time.getTime() > Date.now();
            //       //   // 禁用今天之后的日期(包含今天)
            //       // return time.getTime() > Date.now() - 8.64e7;
            //     },
            //   },
            //   // "value-format": "yyyy-MM-dd",
            //   // "start-placeholder": "开始日期",
            //   // "end-placeholder": "结束日期",
            // },
            // energyType: {
            //   typeName: "el-select",
            //   render: (h) => {
            //     let that = this;
            //     let arr = [];
            //     that.dict?.type?.energy_type.some((item) => {
            //       arr.push(item);
            //     });
            //     // 数据严谨处理,处理后端数据异常情况
            //     let valNum = that.$refs?.form?.getFieldsValue().energyType;
            //     let a = [
            //       h(
            //         "el-select",
            //         {
            //           attrs: {
            //             placeholder: "请选择能耗类型",
            //             value: valNum,
            //             clearable: true,
            //           },
            //           props: ["value"],
            //           on: {
            //             change: (value) => {
            //               that.$refs?.form?.setFieldValue("energyType", value);
            //               that.$forceUpdate();
            //             },
            //           },
            //         },
            //         [
            //           arr.map((item) => {
            //             let { label, value } = item;
            //             return h("el-option", {
            //               props: {
            //                 label,
            //                 value: parseInt(value),
            //                 key: value,
            //               },
            //             });
            //           }),
            //         ]
            //       ),
            //     ];
            //     return h("div", a);
            //   },
            // },
            // subentryType: {
            //   typeName: "el-select",
            //   render: (h) => {
            //     let that = this;
            //     let arr = [];
            //     that.dict?.type?.subentry_type.some((item) => {
            //       arr.push(item);
            //     });
            //     // 数据严谨处理,处理后端数据异常情况
            //     let valNum = that.$refs?.form?.getFieldsValue().subentryType;
            //     let a = [
            //       h(
            //         "el-select",
            //         {
            //           attrs: {
            //             placeholder: "请选择能耗分项",
            //             value: valNum,
            //             clearable: true,
            //           },
            //           props: ["value"],
            //           on: {
            //             change: (value) => {
            //               that.$refs?.form?.setFieldValue(
            //                 "subentryType",
            //                 value
            //               );
            //               that.$forceUpdate();
            //             },
            //           },
            //         },
            //         [
            //           arr.map((item) => {
            //             let { label, value } = item;
            //             return h("el-option", {
            //               props: {
            //                 label,
            //                 value: parseInt(value),
            //                 key: value,
            //               },
            //             });
            //           }),
            //         ]
            //       ),
            //     ];
            //     return h("div", a);
            //   },
            // },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              display: true,
              click: () => this.handlerAudit(null),
            },
          ],
        },
      },
      tableData: {
        column: [],
        data: [],
      },
      defaultColumn: [
        {
          label: "操作",
          width: "240",
          fixed: "right",
          render: (h, scope) => {
            let that = this;
            let a, b, c;
            a = (
              <el-button
                v-hasPermi={["energy:subarea-param:modify"]}
                type="text"
                size="small"
                icon="el-icon-edit"
                onClick={() => {
                  that.handlerAudit(scope.row);
                }}
              >
                编辑
              </el-button>
            );
            if (scope.row.status == 0) {
              b = (
                <el-button
                  v-hasPermi={["energy:subarea-param:modify"]}
                  type="text"
                  size="small"
                  icon="el-icon-bottom"
                  onClick={() => {
                    this.handlerStoporStart(scope.row);
                  }}
                  style="color:#F56C6C"
                >
                  停用
                </el-button>
              );
            } else if (scope.row.status == 1) {
              b = (
                <el-button
                  v-hasPermi={["energy:subarea-param:modify"]}
                  type="text"
                  size="small"
                  icon="el-icon-top"
                  onClick={() => {
                    this.handlerStoporStart(scope.row);
                  }}
                  style="color:#67C23A"
                >
                  启用
                </el-button>
              );
            }
            c = (
              <el-button
                v-hasPermi={["energy:subarea-param:delete"]}
                type="text"
                size="small"
                icon="el-icon-delete"
                onClick={() => {
                  this.handleOperDelete(scope.row);
                }}
                style="color:#F56C6C"
              >
                删除
              </el-button>
            );
            return (
              <div>
                {a}
                {b}
                {c}
              </div>
            );
          },
        },
      ],
      currentPage: 1,
      pageSize: 20,
      total: 0,
    };
  },
  created() {
    this.routerJudge();
  },
  mounted() {
    this.judgePermi();
    this.tableColumnchange();
  },
  methods: {
    routerJudge() {
      let routerflage = this.$route.path;
      switch (routerflage) {
        case "/configuration/standard/household":
          // 分户计量
          this.staticsType = "1";
          break;
        case "/configuration/standard/partition":
          // 分区计量
          this.staticsType = "2";
          break;
        case "/configuration/standard/subentry":
          // 分项计量
          this.staticsType = "4";
          break;
      }
    },
    // 按钮权限判断
    judgePermi() {
      // if (this.$store.state.user.id === 1) {
      //   this.apsForm.formConfig.formSoltButton[2].display = true;
      // } else {
      if (auth.hasPermi("energy:subarea-param:save")) {
        if (this.staticsType != "3") {
          this.apsForm.formConfig.formSoltButton[2].display = false;
        } else {
          this.apsForm.formConfig.formSoltButton[2].display = true;
        }
      }
      // }
    },
    // judgeAdd() {
    //   if (this.staticsType == "3") {
    //     this.apsForm.formConfig.formSoltButton[2].display = true;
    //   }
    // },
    handleClick(tab, event) {
      // console.log(this.staticsType);
      this.tableColumnchange();
    },
    // 表格标签变化
    tableColumnchange() {
      let arr = [];
      this.tableData.column = this.defaultColumn;
      switch (this.staticsType) {
        case "1":
          arr = [
            {
              label: "序号",
              type: "index",
              width: "80",
            },
            {
              prop: "no",
              label: "分户编号",
              width: "150",
              showOverflowTooltip: true,
            },
            {
              prop: "itemType",
              label: "分户类别",
              // showOverflowTooltip: true,
              align: "center",
              width: "150",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_family_splitting_type}
                      value={scope.row.itemType}
                    />
                  </div>
                );
              },
            },
            // {
            //   prop: "",
            //   label: "分户子类",
            //   // width: "150",
            // },
            {
              prop: "ruleContents",
              label: "分户规则",
              // showOverflowTooltip: true,
              minWidth: "300",
            },
            {
              prop: "measureAlone",
              label: "是否单独计量",
              width: "120",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_measure_alone}
                      value={scope.row.measureAlone}
                    />
                  </div>
                );
              },
            },
            {
              prop: "status",
              label: "状态",
              width: "100",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_subarea_status}
                      value={scope.row.status}
                    />
                  </div>
                );
              },
            },
            {
              prop: "updateTime",
              label: "最新更新时间",
              width: "200",
              showOverflowTooltip: true,
              render: (h, scope) => {
                let date = scope.row.updateTime;
                let result;
                if (date != null) {
                  result = formatDate(date);
                } else {
                  result = "";
                }
                return <div>{result}</div>;
              },
            },
            {
              prop: "userName",
              label: "创建人",
              // width: "150",
              showOverflowTooltip: true,
            },
          ];
          this.tableData.column = [...arr, ...this.tableData.column];
          break;
        case "2":
          arr = [
            {
              label: "序号",
              type: "index",
              width: "80",
            },
            {
              prop: "no",
              label: "分区编号",
              width: "150",
              showOverflowTooltip: true,
            },
            {
              prop: "itemType",
              label: "分区类别",
              align: "center",
              width: "150",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_subarea_type}
                      value={scope.row.itemType}
                    />
                  </div>
                );
              },
            },
            {
              prop: "subitemType",
              label: "分区子类",
              align: "center",
              width: "150",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_subarea_child_type}
                      value={scope.row.subitemType}
                    />
                  </div>
                );
              },
            },
            {
              prop: "ruleContents",
              label: "分区规则",
              // showOverflowTooltip: true,
              minWidth: "300",
            },
            {
              prop: "measureAlone",
              label: "是否单独计量",
              width: "120",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_measure_alone}
                      value={scope.row.measureAlone}
                    />
                  </div>
                );
              },
            },
            {
              prop: "status",
              label: "状态",
              width: "100",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_subarea_status}
                      value={scope.row.status}
                    />
                  </div>
                );
              },
            },
            {
              prop: "updateTime",
              label: "最新更新时间",
              width: "200",
              showOverflowTooltip: true,
              render: (h, scope) => {
                let date = scope.row.updateTime;
                let result;
                if (date != null) {
                  result = formatDate(date);
                } else {
                  result = "";
                }
                return <div>{result}</div>;
              },
            },
            {
              prop: "userName",
              label: "创建人",
              // width: "150",
            },
          ];
          this.tableData.column = [...arr, ...this.tableData.column];
          break;
        case "3":
          arr = [
            {
              label: "序号",
              type: "index",
              width: "80",
            },
            {
              prop: "no",
              label: "分类编号",
              width: "150",
              showOverflowTooltip: true,
            },
            {
              prop: "itemType",
              label: "分类类别",
              width: "150",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_type}
                      value={scope.row.itemType}
                    />
                  </div>
                );
              },
            },
            {
              prop: "ruleContents",
              label: "分类规则",
              // showOverflowTooltip: true,
              minWidth: "300",
            },
            {
              prop: "measureAlone",
              label: "是否单独计量",
              width: "120",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_measure_alone}
                      value={scope.row.measureAlone}
                    />
                  </div>
                );
              },
            },
            {
              prop: "status",
              label: "状态",
              width: "100",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_subarea_status}
                      value={scope.row.status}
                    />
                  </div>
                );
              },
            },
            {
              prop: "updateTime",
              label: "最新更新时间",
              width: "200",
              showOverflowTooltip: true,
              render: (h, scope) => {
                let date = scope.row.updateTime;
                let result;
                if (date != null) {
                  result = formatDate(date);
                } else {
                  result = "";
                }
                return <div>{result}</div>;
              },
            },
            {
              prop: "userName",
              label: "创建人",
              // width: "150",
            },
          ];
          let opera = [
            {
              label: "操作",
              width: "240",
              fixed: "right",
              render: (h, scope) => {
                let that = this;
                let b;
                if (scope.row.status == 0) {
                  b = (
                    <el-button
                      v-hasPermi={["energy:subarea-param:modify"]}
                      type="text"
                      size="small"
                      icon="el-icon-bottom"
                      onClick={() => {
                        this.handlerStoporStart(scope.row);
                      }}
                      style="color:#F56C6C"
                    >
                      停用
                    </el-button>
                  );
                } else if (scope.row.status == 1) {
                  b = (
                    <el-button
                      v-hasPermi={["energy:subarea-param:modify"]}
                      type="text"
                      size="small"
                      icon="el-icon-top"
                      onClick={() => {
                        this.handlerStoporStart(scope.row);
                      }}
                      style="color:#67C23A"
                    >
                      启用
                    </el-button>
                  );
                }

                return <div>{b}</div>;
              },
            },
          ];
          this.tableData.column = [...arr, ...opera];
          break;
        case "4":
          arr = [
            {
              label: "序号",
              type: "index",
              width: "80",
            },
            {
              prop: "no",
              label: "分项编号",
              width: "150",
              showOverflowTooltip: true,
            },
            {
              prop: "itemType",
              label: "所属能耗类型",
              align: "center",
              width: "150",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_type}
                      value={scope.row.itemType}
                    />
                  </div>
                );
              },
            },
            {
              prop: "subitemType",
              label: "分项类别",
              align: "center",
              width: "150",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.subentry_type}
                      value={scope.row.subitemType}
                    />
                  </div>
                );
              },
            },
            {
              prop: "ruleContents",
              label: "分户规则",
              // showOverflowTooltip: true,
              minWidth: "300",
            },
            {
              prop: "measureAlone",
              label: "是否单独计量",
              width: "120",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_measure_alone}
                      value={scope.row.measureAlone}
                    />
                  </div>
                );
              },
            },
            {
              prop: "status",
              label: "状态",
              width: "100",
              align: "center",
              render: (h, scope) => {
                return (
                  <div>
                    <dict-tag
                      options={this.dict.type.energy_subarea_status}
                      value={scope.row.status}
                    />
                  </div>
                );
              },
            },
            {
              prop: "updateTime",
              label: "最新更新时间",
              width: "200",
              showOverflowTooltip: true,
              render: (h, scope) => {
                let date = scope.row.updateTime;
                let result;
                if (date != null) {
                  result = formatDate(date);
                } else {
                  result = "";
                }
                return <div>{result}</div>;
              },
            },
            {
              prop: "userName",
              label: "创建人",
              // width: "150",
            },
          ];
          this.tableData.column = [...arr, ...this.tableData.column];
          break;
      }
      this.handlerSearchDetail();
      this.judgePermi();
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
        classifyType: this.staticsType,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      // console.log(query, "qqcs");
      that.$store.commit("app/updateApiCount", "add");
      await getList(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          // console.log(res, 1231);
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20080");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {};
      // const { date, ...other } = this.$refs?.form?.getFieldsValue();
      data.status = this.$refs?.form?.getFieldsValue().status;
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    // 编辑/新增
    handlerAudit(row) {
      // console.log(row);
      if (row != null) {
        // 修改
        this.rowID = row?.id ?? "";
      } else {
        // 新增
        this.rowID = "";
      }
      setTimeout(() => {
        this.visible = true;
      }, 100);
    },
    // 启用/停用
    handlerStoporStart(row) {
      let params = {
        id: row.id,
        status: row.status == 0 ? 1 : 0,
      };
      putSubstatus(params)
        .then((res) => {
          // console.log(res);
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          this.initData();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20086");
        });
    },
    //删除
    handleOperDelete(row) {
      let that = this;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      that.$modal
        .confirm(text)
        .then(() => {
          // console.log(row, "2244");
          deleteSub(row.id)
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.$message.success("已删除!");
              that.initData();
            })
            .catch((err) => {
              // this.$message.error("系统错误,请联系管理员!20084");
            });
        })
        .catch(() => {});
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    close(status) {
      this.visible = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>
<style scoped lang="scss">
.lb_layout {
  padding: 10px 20px;
}
::v-deep .text-tabs {
  margin-top: 5px;
  margin-bottom: -5px;
  .el-tabs__active-bar {
    width: 79px;
  }
  .el-tabs__item {
    font-size: 20px;
    font-weight: 600;
    opacity: 0.8;
  }
}
// .flex {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   margin-bottom: 16px;
//   .el-radio {
//     margin-right: 100px;
//   }
//   .title {
//     color: #22568f;
//     font-size: 14px;
//   }
// }
</style>
